package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.core.domain.dto.RoleDTO;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.system.constants.DyRoleKeyConstants;
import com.ruoyi.system.domain.vo.DyAnchorVo;
import com.ruoyi.system.domain.vo.DyCustomerSumVo;
import com.ruoyi.system.mapper.DyAnchorMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.IDyCommonService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.domain.bo.DyCustomerBo;
import com.ruoyi.system.domain.vo.DyCustomerVo;
import com.ruoyi.system.domain.DyCustomer;
import com.ruoyi.system.mapper.DyCustomerMapper;
import com.ruoyi.system.service.IDyCustomerService;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

import static com.ruoyi.common.helper.LoginHelper.getLoginUser;

/**
 * 客服Service业务层处理
 *
 * @author ruoyi
 * @date 2024-06-20
 */
@RequiredArgsConstructor
@Service
public class DyCustomerServiceImpl implements IDyCustomerService {

    private final DyCustomerMapper baseMapper;

    private final DyAnchorMapper dyAnchorMapper;

    private final SysUserMapper sysUserMapper;

    @Autowired
    IDyCommonService iDyCommonService;

    /**
     * 查询客服
     */
    @Override
    public DyCustomerVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询客服列表
     */
    @Override
    public TableDataInfo<DyCustomerVo> queryPageList(DyCustomerBo bo, PageQuery pageQuery, LoginUser loginUser) {
        RoleDTO roleDTO = iDyCommonService.getFirstRole(loginUser.getRoles());
        if (ObjectUtil.isEmpty(roleDTO)){
            throw new ServiceException("无数据查看权限");
        }

        LambdaQueryWrapper<DyCustomer> lqw = buildQueryWrapper(bo);

        if (roleDTO.getRoleKey().equals(DyRoleKeyConstants.roleKeySubCompany)){
            LambdaQueryWrapper<SysUser> queryWrapperUser = new LambdaQueryWrapper<>();
            queryWrapperUser.eq(SysUser::getDeptId,loginUser.getDeptId());
            List<SysUser> userList = sysUserMapper.selectList(queryWrapperUser);
            lqw.in(DyCustomer::getAnchorId,userList);

            RoleDTO roleDTO2 = iDyCommonService.getRoleByKey(loginUser.getRoles(),DyRoleKeyConstants.roleKeyYunYing);
            if (ObjectUtil.isNotEmpty(roleDTO2)){
                lqw.eq(DyCustomer::getCreateBy,loginUser.getUsername());
            }
        } else if (roleDTO.getRoleKey().equals(DyRoleKeyConstants.roleKeyYunYing)){
            lqw.eq(DyCustomer::getCreateBy,loginUser.getUsername());
        }

        lqw.orderByDesc(DyCustomer::getUpdateTime);
        Page<DyCustomerVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        if (CollectionUtil.isNotEmpty(result.getRecords())){
            List<Long> authorIds = result.getRecords().stream().map(DyCustomerVo::getAnchorId).collect(Collectors.toList());
            List<DyAnchorVo> anchorVos = dyAnchorMapper.selectVoBatchIds(authorIds);
            Map<Long,DyAnchorVo> anchorMap = new HashMap<>();
            if (CollectionUtil.isNotEmpty(anchorVos)){
                anchorMap = anchorVos.stream().collect(Collectors.toMap(DyAnchorVo::getId,item -> item,(k1,k2) -> k1));
            }
            for (DyCustomerVo item : result.getRecords()){
                if (ObjectUtil.isNotEmpty(anchorMap.get(item.getAnchorId())) && ObjectUtil.isNotEmpty(anchorMap.get(item.getAnchorId()).getName())){
                    item.setAnchorName(anchorMap.get(item.getAnchorId()).getName());
                }
                BigDecimal orderNum = BigDecimal.valueOf(item.getOrderNum());
                BigDecimal giftNum = BigDecimal.valueOf(item.getGiftNum());
                if (orderNum.compareTo(BigDecimal.ZERO) > 0 && giftNum.compareTo(BigDecimal.ZERO) > 0) {
                    BigDecimal perTransForm = orderNum.divide(giftNum, 2, BigDecimal.ROUND_HALF_UP);
                    // 转化率等于单量除以礼物数
                    item.setPerTransForm(perTransForm);
                }

                BigDecimal arrivalsNum = BigDecimal.valueOf(item.getArrivalsNum());
                if (arrivalsNum.compareTo(BigDecimal.ZERO) > 0 && giftNum.compareTo(BigDecimal.ZERO) > 0){
                    BigDecimal perArrivals = arrivalsNum.divide(giftNum,2,BigDecimal.ROUND_HALF_UP);
                    // 转化率等于单量除以礼物数
                    item.setPerArrivals(perArrivals);
                }
            }
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询客服列表
     */
    @Override
    public List<DyCustomerVo> queryList(DyCustomerBo bo) {
        LambdaQueryWrapper<DyCustomer> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<DyCustomer> buildQueryWrapper(DyCustomerBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<DyCustomer> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getAnchorId() != null, DyCustomer::getAnchorId, bo.getAnchorId());
        lqw.eq(bo.getStartTime() != null, DyCustomer::getStartTime, bo.getStartTime());
        lqw.eq(bo.getLiveTime() != null, DyCustomer::getLiveTime, bo.getLiveTime());
        lqw.eq(bo.getNum() != null, DyCustomer::getNum, bo.getNum());
        lqw.eq(bo.getGiftNum() != null, DyCustomer::getGiftNum, bo.getGiftNum());
        lqw.eq(bo.getOrderNum() != null, DyCustomer::getOrderNum, bo.getOrderNum());
        if (ObjectUtil.isNotEmpty(bo.getStartTimeStart()) && ObjectUtil.isNotEmpty(bo.getStartTimeEnd())){
            lqw.between(DyCustomer::getStartTime,bo.getStartTimeStart() ,bo.getStartTimeEnd());
        }
        return lqw;
    }

    /**
     * 新增客服
     */
    @Override
    public Boolean insertByBo(DyCustomerBo bo) {
        DyCustomer add = BeanUtil.toBean(bo, DyCustomer.class);
        validEntityBeforeSave(add);
        add.setCreateId(getLoginUser().getUserId());
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改客服
     */
    @Override
    public Boolean updateByBo(DyCustomerBo bo) {
        DyCustomer update = BeanUtil.toBean(bo, DyCustomer.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    @Override
    public DyCustomerSumVo getSumCustomer(DyCustomerBo bo) {
        DyCustomerSumVo dyCustomerSumVo = baseMapper.getSumCustomer(bo);
        if (ObjectUtil.isNotEmpty(dyCustomerSumVo)){
            BigDecimal orderNum = BigDecimal.valueOf(dyCustomerSumVo.getOrderNum());
            BigDecimal giftNum = BigDecimal.valueOf(dyCustomerSumVo.getGiftNum());
            if (orderNum.compareTo(BigDecimal.ZERO) > 0 && giftNum.compareTo(BigDecimal.ZERO) > 0){
                BigDecimal perTransForm = orderNum.divide(giftNum,2,BigDecimal.ROUND_HALF_UP);
                dyCustomerSumVo.setPerTransForm(perTransForm);
            }
            BigDecimal arrivalsNum = BigDecimal.valueOf(dyCustomerSumVo.getArrivalsNum());
            if (arrivalsNum.compareTo(BigDecimal.ZERO) > 0 && giftNum.compareTo(BigDecimal.ZERO) > 0){
                BigDecimal perArrivals = arrivalsNum.divide(giftNum,2,BigDecimal.ROUND_HALF_UP);
                dyCustomerSumVo.setPerArrivals(perArrivals);
            }
        }
        return dyCustomerSumVo;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(DyCustomer entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除客服
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
